#include "common.h"

int file_length(FILE *f) {
	int pos;
	int end;

	pos = ftell (f);
	fseek (f, 0, SEEK_END);
	end = ftell (f);
	fseek (f, pos, SEEK_SET);

	return end;
}

int isNumeric(char * argument, int * number, int negativeAllowed) {
	char itoa[10];
	int i=0,len;
	len = strlen(argument);
	if (argument[0] == '-' && negativeAllowed)
		i++;
	do {
		if (!isdigit(argument[i]))
			return 0;
		i++;
	} while (i < len);
	
	sprintf(itoa, "%d", atoi(argument));
	if (strcmp(itoa,argument) != 0) {
		return 0;
	}
	
	if (number != NULL)
		*number = atoi(argument);
	return 1;
}

char *trimwhitespace(char *str)
{
  char *end;

  if (str == NULL)
	  return "";

  // Trim leading space
  while(isspace(*str)) str++;

  if(*str == 0)  // All spaces?
    return str;

  // Trim trailing space
  end = str + strlen(str) - 1;
  while(end > str && isspace(*end)) end--;

  // Write new null terminator
  *(end+1) = 0;

  return str;
}

void strip_newline(char *str, int size) {
	int i;

	for (i = 0; i < size; i++) {
		if (str[i]=='\n') {
			str[i] = '\0';
			return;
		}
	}
}

int findMemberIndex(char * text, char ** arr, int arr_size) {
	int i;
	for (i = 0; i < arr_size; i++) {
		if (strcmp(text, arr[i]) == 0)
			return i;
	}
	return -1;
}

int iLog2 (int val) {
    unsigned int ret = -1;
    while (val != 0) {
        val >>= 1;
        ret++;
    }
    return ret;
}



void printBuffer(FILE * target, unsigned char * data, int size) {
	int i;
	fprintf(target, "0x");
	for (i = 0; i < size; i++) {
		fprintf(target, "%.2X ", data[i]);
	}
}

void printBuffer2(FILE * target, unsigned char data[], int size) {
	int i;
	fprintf(target, "0x");
	for (i = 0; i < size; i++) {
		fprintf(target, "%.2X ", data[i]);
	}
}